<?php
namespace App\Admin\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
use Illuminate\Validation\Rules\Password;

use App\Admin\Controllers\Controller;
use App\Admin\Models\User;
use App\Admin\Admin;


class ProfileController extends Controller
{

	// GET http://www.llc.com/api/admin/profile
	public function show(Request $request)
	{
		return Admin::success(Admin::user());
	}

	// PUT http://www.llc.com/api/admin/profile
	public function update(Request $request)
	{
		$user = Admin::user();

        $unique = Rule::unique(User::class)->ignore($user);
        $validated = Validator::make($request->all(), [
            'email'  => ['required', 'email', 'max:255', $unique],
            'mobile' => ['nullable', 'digits:11', 'max:255', $unique],
            'name'   => ['required', 'alpha_num', 'max:255'],
            'profile_photo_path'   => 'nullable|string|max:255',
            // 'password' => ['nullable', Password::min(8)->max(20)->letters()],
        ])->validate();


        
		$user->forceFill($validated);
        $isDirty = $user->isDirty();
        $user->save();

		return Admin::success($user, 0, $isDirty?'个人资料更新成功':'数据没有变化');
	}


	public function store(Request $request)
	{
		$validated = $request->validate([
            'file' => [
            	'required','file','image','max:12000',
			    'dimensions:max_width=5000,max_height=5000,min_width=50,min_height=50'
            ],
		], [
			'image' => '上传的不是图片',
			'max'   => '图片最大:max KB之间',
			'dimensions' => '图片尺寸错误，长宽必须在50-500像素之间',
		]);

		// 保存到公开磁盘
		$file = $request->file('file');
		$path = $file->storePublicly(date('Y/md'), 'public');

		return Admin::success([
			'path' => $path,
			'url' => Storage::disk('public')->url($path)
		]);
	}


	public function password(Request $request)
	{
		$validated = $request->validate([
            'current_password'  => ['required', 'current_password:admin'],
            'password' => ['required', 'confirmed', Password::min(8)->max(20)->letters()],
            'password_confirmation'   => 'required|string|max:255',
		]);

        $user = Admin::user();
        $user->password = $validated['password'];
        $user->save();

		return Admin::success();
	}
}
